package com.skyk.config.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.skyk.util.context.UserContext;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;

/*自动填充处理器*/
//在插入或更新数据时自动填充某些字段

/*利用已经实现的ThreadLocal用户管理(UserContext)，优化自动填充用户信息*/
/*在用户登录成功后, ThreadLocal用户管理(UserContext)存储着 用户信息 , 在插入或更新时,自动将createUser,updateUser进行填充*/

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        //插入时自动填充字段
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "createUser", String.class, UserContext.getUser().getUsername());
        this.strictInsertFill(metaObject, "updateUser", String.class, UserContext.getUser().getUsername());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //更新时自动填充字段
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, "updateUser", String.class, UserContext.getUser().getUsername());

    }
}
